﻿@Cofe ?= {}

$ = jQuery

class EventListener extends Spine.Controller    
  currentEventId : null
  eventsFeedUrl : '/api/events'
  feedRefreshTime : 15000

  constructor : (constructionParam) ->    
    #console.log "constructor"
    @bind("refreshed", () => setTimeout(@refresh, @feedRefreshTime))
    @bind("error", () => setTimeout(@refresh, @feedRefreshTime))

    setTimeout(@refresh, 5)
    super
  

  triggerRefreshed : () =>
    if @currentEventId isnt @recentEventId
      log.debug "FeedController: Current : " + @currentEventId + " Recent : " + @recentEventId
      @currentEventId = @recentEventId
    @trigger("refreshed", @)
    @workingFeedItem

  #trigger event event when there's an event.
  processEventItem : (eventItem) =>
    @trigger("event", @, eventItem)

  #keep Process feedItem and eventItem until feedItem do not have prevFeed or a matched eventId is found.
  processFeedItem : (feedItem) =>
    if feedItem.feed.url is @eventsFeedUrl
      @recentEventId = feedItem.eventItems[0].event.id

    if @currentEventId is null  
        return @triggerRefreshed()

    for ei in feedItem.eventItems
      if ei.event.id is @currentEventId 
        return @triggerRefreshed()
      else @processEventItem(ei)

    if !feedItem.hasPrev 
        @trigger("error", @)
        log.error "FeedController: Cannot find " + @currentEventId
        @currentEventId = null #reset id        
        return;

    @workingFeedItem?.unbind("loaded")
    @workingFeedItem = feedItem.prev()    
    @workingFeedItem.bind("loaded", @processFeedItem)
    @workingFeedItem.load()

  refresh : () =>
    log.trace "EventListener: Refreshing feed"
    @workingFeedItem?.unbind("loaded")
    @workingFeedItem = Cofe.FeedItem.fromUrl(@eventsFeedUrl)    
    @workingFeedItem.bind("loaded", @processFeedItem)
    @workingFeedItem.load()

Cofe.EventListener = EventListener